import express from 'express';
import fs from 'fs';
import Path from 'path';

var router = express.Router();

/* GET home page. */
router.get(/\/\S+\.html/i, function(req, res, next) {
  res.render('template', {
    src:req.originalUrl.substring(0,req.originalUrl.length-5)+"/index.js"
  });
});

router.get(/\/\S+\.js/i, function(req, res, next) {
  if (req.query.callback){
    let views=res.app.get("views");
    let path=Path.join(views,req.path);
    fs.readFile(path,(err,buffer)=>{
      if (err) next();
      else {
          let text=buffer.toString("UTF-8");
          if (text.endsWith(";")) text=text.substring(0,text.length-1);
          res.send(req.query.callback+"("+text+");");
      }
    })
  }else {
    next();
  }
});
module.exports = router;
